#!/usr/bin/perl -w
package clreqd_modules;
# vi:SetSyn("perl")

#########################################################################
# This rountine takes one or more records packed on the command 	#
# line and applies them to the database table in question (which must	#
# already exist).							#
#									#
# Arguments are:							#
# table									#
# [database]								#
# [clause]								#
#									#
# database  default is 'config' can be set to 'status'.			#
# table	    The name of the table to dump.				#
# clause    SQL to determine which matching records to dump.		#
#									#
# The output generated is suitable for the 'data' argument of the	#
# load_table request.							#
#									#
# field|value|field|value						#
#									#
# Multiple records are separated by new lines, and then the whole	#
# thing is hex-encoded.							#
#									#
#########################################################################

use cldb;
use clmasterdefaults;
use Data::Dumper;

sub dump_table {
my %ARGS=@_;
my $f;
my $clause="";

	if(!exists($ARGS{DATABASE})) { $ARGS{DATABASE}="config"; }
	if(exists($ARGS{CLAUSE})) {
		$clause="WHERE $ARGS{CLAUSE}";
	}

	if(! -f "$::ENV{TRUECL_CFG}/$ARGS{DATABASE}.db") {
		return("FAIL Failed to open database '$::ENV{TRUECL_CFG}/$ARGS{DATABASE}.db'!");
	}

	#################################################################
	# Database does exist, so open it up ready for reading.	#
	#################################################################

	my $db=new cldb("$::ENV{TRUECL_CFG}/$ARGS{DATABASE}.db");
	if(!defined($db)) {
		return("FAIL Unable to open database '$ARGS{DATABASE}.db':\n" . cldb::error);
	}
	::msg("Opened database connection to '$::ENV{TRUECL_CFG}/$ARGS{DATABASE}.db'.");

	#################################################################
	# Ensure the table exists and abort if not.			#
	#################################################################

	if(! $db->exists("table","$ARGS{TABLE}")) {
		return("FAIL Config database missing '$ARGS{TABLE}' table.");
	}
	
	#################################################################
	# If the truncate = 1 then we need to start the transaction	#
	# and remove all existing records.				#
	#################################################################

	my @L=();
	::msg("SELECT * FROM $ARGS{TABLE} $clause;");
	my $res=$db->get_rows("SELECT * FROM $ARGS{TABLE} $clause;");
	for (@$res) {
		my $f;
		my @V=();
		for $f (sort(keys %{$_})) {
			push @V,$f,$_->{$f};
		}
		push @L,join("|",@V);
	}
	$db->disconnect; $db=undef;
	my $data=unpack("H*",join("\n",@L));
	return "OK\n$data";
}

1;
